jpa 生成uuid的主键

您所在的位置:网站首页 jpa uuid 主键 jpa 生成uuid的主键

jpa 生成uuid的主键

2024-07-03 09:14| 来源: 网络整理| 查看: 265

1.将数据库中的主键,设置为varchar(32)。

2.在entity中类头部写入@GenericGenerator(name = "jpa-uuid", strategy = "uuid")

3.在entity中id主键顶部写入@GeneratedValue(generator = "jpa-uuid"),注意generator中的值必须与注释@GenericGenerator中name属性完全一致。

4.设置entity中主键ID为string类型。设置长度为32

5.GenericGenerator是Hibernate中的注释,有两个参数。name是system-uuid“” ,策略strategy是uuid 。 static {

GENERATORS.put("uuid", UUIDHexGenerator.class); GENERATORS.put("hilo", TableHiLoGenerator.class); GENERATORS.put("assigned", Assigned.class); GENERATORS.put("identity", IdentityGenerator.class); GENERATORS.put("select", SelectGenerator.class); GENERATORS.put("sequence", SequenceGenerator.class); GENERATORS.put("seqhilo", SequenceHiLoGenerator.class); GENERATORS.put("increment", IncrementGenerator.class); GENERATORS.put("foreign", ForeignGenerator.class); GENERATORS.put("guid", GUIDGenerator.class); GENERATORS.put("uuid.hex", UUIDHexGenerator.class); //uuid.hex is deprecated GENERATORS.put("sequence-identity", SequenceIdentityGenerator.class); }

上面的12种策略,再加上native,一共是13种。

[email protected]注解属于一个JPA接口(从JAVA EE 5开始,存在于javax.persistence包下),其接口下包含了两个抽象的参数,GenerationType类型的strategy和String类型的generator,并且两个参数都有相应的默认值。

8.GenerationType同样也位于javax.persistence包下,并且还继承了Enum枚举类,然后其中有4个值供我们使用,分别是:

TABLE:使用一个特定的数据库表格来保存主键。

SEQUENCE:根据底层数据库的序列来生成主键,条件是数据库支持序列。 这个值要与generator一起使用,generator 指定生成主键使用的生成器(可能是orcale中自己编写的序列)。

IDENTITY:主键由数据库自动生成(主要是支持自动增长的数据库,如mysql)

AUTO:主键由程序控制,也是GenerationType的默认值。

9.两个数据库对GenerationType的支持

mysql

GenerationType.TABLE

GenerationType.AUTO

GenerationType.IDENTITY

不支持GenerationType.SEQUENCE

oracle

strategy=GenerationType.AUTO

GenerationType.SEQUENCE

GenerationType.TABLE

不支持GenerationType.IDENTITY



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3